#pragma once

#include "stdafx.h"
#include "MessageSubscriber.h"
#include "Messages.h"

class MessageArray
{
public:
    static MessageArray* Instance()
    {
        if (instance == NULL)
            instance = new MessageArray();
        return instance;
    }
    void addSubscriber(MessageSubscriber* _subscriber)
    {
        for (std::vector<MessageSubscriber *>::const_iterator iter = subscriber.begin();
            iter != subscriber.end();
            ++iter)
        {
            if (*iter == _subscriber)
                return;
        }
        subscriber.push_back(_subscriber);
    }
    void fireNewMessage()
    {
        for (std::vector<MessageSubscriber *>::const_iterator iter = subscriber.begin();
            iter != subscriber.end();
            ++iter)
        {
            if ((*iter)->fire())
            {
                messages.pop_back();
                return;
            }
        }
        messages.pop_back();
    }
    U_MESSAGE getMessage()
    {
        if (messages.size() != 0)
            return *(messages.rbegin());
        else
            return NILMESSAGE;
    }
    void postMessage(U_MESSAGE msg)
    {
        messages.push_back(msg);
        fireNewMessage();
    }
protected:
    MessageArray(void);
    virtual ~MessageArray(void);
private:
    static MessageArray *instance;
    std::vector<MessageSubscriber *> subscriber;
    std::vector<U_MESSAGE> messages;
};
